<template>
  <el-row class="login-container" justify="center" align="middle">
    <el-card style="max-width: 480px;">
      <template #header>
        <div class="card-header">
          <img :src="imgUrl" alt="">
        </div>
        <div class="jump-link">
          <el-link type="primary" @click="handleChange">{{formType?'返回登录':'注册账号'}}</el-link>
        </div>
        <el-form  :model="loginForm" style="max-width: 600px; padding:0 20px ;" :rules="rules" ref="loginFormRef">
          <el-form-item prop="userName">
            <el-input v-model="loginForm.userName" placeholder="请输入手机号" :prefix-icon="User" />
          </el-form-item>

          <el-form-item prop="passWord">
            <el-input v-model="loginForm.passWord" type="password" placeholder="请输入密码" :prefix-icon="Lock" />
          </el-form-item>

          <el-form-item v-if="formType" prop="validCode">
            <el-input v-model="loginForm.validCode"  placeholder="请输入验证码" :prefix-icon="Lock">
              <template #append>
              <span @click="countDownChange">{{countDown.validText}}</span>
              </template>
            </el-input>
            
          </el-form-item>
          <el-form-item>
            <el-button type="primary" style="width:100%;" @click="submitForm(loginFormRef)">{{!formType?'登录':'注册账号'}}
            </el-button>
          </el-form-item>
        
        
        </el-form>

      </template>
    </el-card>

  </el-row>
</template>

<script setup>
import {ref,reactive,computed,toRaw} from 'vue'
import {Lock,User} from '@element-plus/icons-vue'
import {userAuthentication,login,menuPermissions} from '@/api/index'
import { useRouter } from 'vue-router';
import { useStore } from 'vuex';
const router=useRouter()
const store=useStore()

const routerList=computed(()=>store.state.menu.routerList)
const imgUrl=new URL('../../../public/login-head.png', import.meta.url).href
//表单
const loginForm=reactive({
  userName: '',
  passWord:'',
  validCode:''
  
})

// rules校验规则
const rules=reactive({
  userName:[{
    validator: (rule, value, callback) => {
      if(value === ''){
        callback(new Error('请输入手机号'))
      }else{
        const phoneReg=/^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/
        if(!phoneReg.test(value)){
          callback(new Error('请输入正确的手机号'))
        }else{
          callback()
        }

      }
      
    },
    trigger: 'blur'
  }],
  passWord:[{
    validator: (rule, value, callback) => {
      if(value === ''){
        callback(new Error('请输入密码'))
      }else{
        const phoneReg=/^[a-zA-Z0-9_-]{4,16}$/
        if(!phoneReg.test(value)){
          callback(new Error('请输入正确的密码'))
        }else{
          callback()
        }

      }
      
    }, trigger: 'blur'
    
  }]
})


// 倒计时
const countDown=reactive({
  validText:'获取验证码',
  time:60
})
let flag=false
const  countDownChange=()=>{
  if(flag){
    return
  }
  const phoneReg=/^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/
  if(!loginForm.userName||!phoneReg.test(loginForm.userName)){
    return ElMessage({
      message: '请输入正确的手机号',
      type: 'warning'
    })

  }
  if(countDown.time===60){
    countDown.validText='重新获取'
    let timer=setInterval(()=>{
      countDown.time--
      countDown.validText=`${countDown.time}秒后重新获取`
      if(countDown.time===0){
        clearInterval(timer)
        countDown.validText='获取验证码'
        countDown.time=60
        flag=false
      }
    },1000)
    flag=true
    
  }
}

// 切换登录，注册
// 0登录  1注册
const loginFormRef=ref()
const formType=ref(0)
const handleChange=()=>{
  formType.value=formType.value ? 0 : 1
  
}

const submitForm = async (foemEl)=>{
  if(!foemEl) return
  await foemEl.validate((vaild,fields)=>{
    if(vaild){
      if(formType.value){
        userAuthentication(loginForm).then(({data})=>{
          if(data.code===10000){
            ElMessage.success('注册成功,请登录')
            formType.value=0

          }
          
        })

      }else{
        login(loginForm).then(({data})=>{
          if(data.code===10000){
            ElMessage.success('登录成功')
            localStorage.setItem('pz_token',data.data.token)
            localStorage.setItem('pz_userInfo',JSON.stringify(data.data.userInfo))
            menuPermissions().then(({data})=>{
              store.commit('dynamicMenu',data.data)
              toRaw(routerList.value).forEach(item=>{
                router.addRoute('main',item)
              })
              router.push('/')

            })
           

          }

        })

      }
  
    }else{
      ElMessage.error('请输入正确的信息')
    }

  }
)

  
}

</script>

<style lang="less" scoped>

:deep(.el-card__header) {
    padding: 0
  }
  .login-container {
    height: 100vh;
    .card-header{
      background-color: #899fe1;
      img {
        width: 430px;
      }
    }
    .jump-link {
      text-align: right;
      margin-bottom: 10px;
    }
  }

.card-header img {
  width: 100%;
  max-width: 430px;
}
  </style>
  